package me.timlong.controller;

import me.timlong.controller.viewObject.ItemVO;
import me.timlong.error.BusinessException;
import me.timlong.response.CommonReturnType;
import me.timlong.service.CacheService;
import me.timlong.service.PromoService;
import me.timlong.service.impl.ItemServiceImpl;
import me.timlong.service.model.ItemModel;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Controller("item")
@RequestMapping("/item")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")  // 跨域请求，前后端分离
public class ItemController extends BaseController {

    @Autowired
    private ItemServiceImpl itemService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private PromoService promoService;

    @RequestMapping(value = "/create", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonReturnType createItem(@RequestParam(name = "title") String title,
                                       @RequestParam(name = "price") BigDecimal price,
                                       @RequestParam(name = "stock") Integer stock,
                                       @RequestParam(name = "description") String description,
                                       @RequestParam(name = "imgUrl") String imgUrl) throws BusinessException {

        // 封装service层的ItemModel用于商品的入库
        ItemModel itemModel = new ItemModel();
        itemModel.setTitle(title);
        itemModel.setPrice(price);
        itemModel.setStock(stock);
        itemModel.setDescription(description);
        itemModel.setImgUrl(imgUrl);

        ItemModel itemModelForReturn = itemService.createItem(itemModel);

        // 将出创建完成的商品信息封装进入ItemVO返回给前端
        ItemVO itemVO = this.convertItemVOFromItemModel(itemModelForReturn);
        return new CommonReturnType().create(itemVO);
    }

    // Get方式请求服务一般不改变服务端的数据
    @RequestMapping(value = "/get", method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType getItem(@RequestParam(name = "id") Integer id) {

        // 采用多级缓存策略

        // 本地缓存
        ItemModel itemModel = (ItemModel) cacheService.getFromCommonCache("item_" + id);

        if(null == itemModel) {
            itemModel = (ItemModel) redisTemplate.opsForValue().get("item_" + id);
            if(null == itemModel) {
                itemModel = this.itemService.getItemById(id);
                redisTemplate.opsForValue().set("item_" + id, itemModel);
                // 设置redisTemplate 的过期时期
                redisTemplate.expire("item_" + id, 10, TimeUnit.MINUTES);
            }
            // 填充本地缓存 GUA Cache
            cacheService.setCommonCache("item_" + id, itemModel);
        }
        ItemVO itemVO = this.convertItemVOFromItemModel(itemModel);
        return CommonReturnType.create(itemVO);
    }

    @RequestMapping(value = "/list", method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType listItems() {
        List<ItemModel> itemModels = this.itemService.listItem();
        List<ItemVO> itemVOS = itemModels.stream().map(itemModel -> this.convertItemVOFromItemModel(itemModel)).collect(Collectors.toList());
        return CommonReturnType.create(itemVOS);
    }


    private ItemVO convertItemVOFromItemModel(ItemModel itemModel) {
        if (null == itemModel)
            return null;
        ItemVO itemVO = new ItemVO();
        BeanUtils.copyProperties(itemModel, itemVO);
        if (null != itemModel.getPromoModel()) {
            // 有正在或即将进行的秒杀活动
            itemVO.setPromoId(itemModel.getPromoModel().getId());
            itemVO.setPromoStatus(itemModel.getPromoModel().getStatus());
            itemVO.setPromoPrice(itemModel.getPromoModel().getPromoItemPrice());

            // joda DateTime转化为字符串的时间的格式
            itemVO.setStartDate(itemModel.getPromoModel().getStartTime().toString(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")));
        } else {
            itemVO.setPromoStatus(0);
        }
        return itemVO;
    }


    // Get方式请求服务一般不改变服务端的数据
    @RequestMapping(value = "/publishpromo", method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType publishPromo(@RequestParam(name = "id") Integer id) {
        promoService.publishPromo(id);
        return CommonReturnType.create(null);
    }
}
